/**
 *====================================================
 * 文件名称: FinanceBulkstockActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月26日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.project.action.v1;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.httpclient.ServiceClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.context.FinanceBaseAction;
import com.yuexunit.finance.context.FinanceConstant;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.project.action.v1.dto.BulkstockCastor;
import com.yuexunit.finance.project.action.v1.model.FinanceBulkstock;
import com.yuexunit.finance.project.action.v1.model.FinanceBulkstockPublic;
import com.yuexunit.finance.project.action.v1.model.input.BillInfo;
import com.yuexunit.finance.project.action.v1.model.output.ContainerBulkstock;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInfos;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventory;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventoryHistory;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventoryImages;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventoryLog;
import com.yuexunit.finance.project.action.v1.model.output.ContainerInventoryTrackingDetail;
import com.yuexunit.finance.project.action.v1.model.output.ImagesDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupBulkstockInfo;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryHistoryEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryTallyEntity;
import com.yuexunit.finance.project.entity.DeliveryNoticeEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceChangebillLogEntity;
import com.yuexunit.finance.project.entity.FinanceContainerLogEntity;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.SupervisionStateEnum;
import com.yuexunit.finance.project.service.FinanceChangeBillLogService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.StringUtil;

import net.sf.json.JSONArray;

/**
 * @ClassName: FinanceBulkstockActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月26日 下午12:13:42
 */
@Implements(FinanceBulkstockActionApi.class)
public class FinanceBulkstockActionApiImpl extends FinanceBaseAction implements FinanceBulkstockActionApi {
	public static Logger logger = LoggerFactory.getLogger(FinanceBulkstockActionApiImpl.class);
	
	private PageList<FinanceBulkstock> toFinanceBulkstockPageList(PageList<FinanceBulkstockEntity> bulkstockList, PageCriteria page) {
		PageList<FinanceBulkstock> results = new PageList<FinanceBulkstock>(page, bulkstockList.getTotalRecordCount());
		for (FinanceBulkstockEntity entity : bulkstockList) {
			results.add(BulkstockCastor.toFinanceBulkstock(entity));
		}
		return results;
	}

	@Override
	public PageList<FinanceBulkstock> inquireFinanceBulkstockPageList(Long financeId, String keyword, PageCriteria page) {
		PageList<FinanceBulkstockEntity> bulkstockList = financeBulkstockService.inquireFinanceBulkstockPageList(financeId, keyword, page);
		return toFinanceBulkstockPageList(bulkstockList, page);
	}

	@Override
	public PageList<FinanceBulkstockPublic> inquirePublicFinanceBulkstockPageList(String bulkstockName, String specification, String originPlace, PageCriteria page) {
		PageList<FinanceBulkstockEntity> bulkstockList = financeBulkstockService.inquirePublicFinanceBulkstockPageList(bulkstockName, specification, originPlace, page);
		PageList<FinanceBulkstockPublic> results = new PageList<>(page, bulkstockList.getTotalRecordCount());
		for (FinanceBulkstockEntity entity : bulkstockList) {
			results.add(BulkstockCastor.toFinanceBulkstockPublic(entity));
		}
		return results;
	}

	// ====================================================================================================//
	@Override
	public List<ContainerInventory> inquireWaitLoanNoticeBulkstockInventoryList(Long financeId) {
		List<ContainerInventoryEntity> list = containerInventoryService.inquireWaitLoanNoticeContainerInventoryList(financeId);
		List<ContainerInventory> results = new ArrayList<>();
		for (ContainerInventoryEntity bie : list) {
			results.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		return results;
	}
	
	@Override
	public PageList<ContainerInventory> inquireWaitLoanNoticeBulkstockInventoryPageList(Long financeId, PageCriteria page) {
		PageList<ContainerInventoryEntity> list = containerInventoryService.inquireWaitLoanNoticeContainerInventoryPageList(financeId, page);
		PageList<ContainerInventory> results = new PageList<>(page, list.getTotalRecordCount());
		for (ContainerInventoryEntity bie : list) {
			results.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		return results;
	}

	@Override
	public List<ContainerInventory> inquireWaitTransportNoticeBulkstockInventoryList(Long financeId) {
		List<ContainerInventoryEntity> list = containerInventoryService.inquireWaitTransportContainerInventoryList(financeId);
		List<ContainerInventory> results = new ArrayList<>();
		for (ContainerInventoryEntity bie : list) {
			results.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		return results;
	}

	@Override
	public List<ContainerInventory> inquireWaitDeliveryBulkstockInventoryList(Long deliveryNoticeId) {
		DeliveryNoticeEntity deliveryNotice = deliveryNoticeService.inquireDeliveryNoticeDetail(deliveryNoticeId);
		List<ContainerInventoryEntity> list = containerInventoryService.inquireWaitDeliveryBulkstockInventoryList(deliveryNotice);
		List<ContainerInventory> results = new ArrayList<>();
		for (ContainerInventoryEntity bie : list) {
			results.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		return results;
	}
	
	@Override
	public List<PickupBulkstockInfo> inquireBulkstockInventoryList(Long enterpriseId, Integer productType, String bulkstockName, Long bulkstockInfoId, String warehouseName) {
		StringBuffer sql = new StringBuffer("SELECT * FROM view_fin_pickupable_bulkstock v WHERE 1 = 1");
//		sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
//		sql.append(" AND a.ENTERPRISE_ID =").append(enterpriseId);
//		if (StringUtil.isNotBlank(warehouseName)) {
//			sql.append(" AND a.WAREHOUSE_NAME = '").append(warehouseName).append("' ");
//		}
//		sql.append(" AND c.PRODUCT_TYPE =").append(productType);
//		if (StringUtil.isNotBlank(bulkstockName)) {
//			sql.append(" AND BULKSTOCK_NAME like '%").append(bulkstockName + "%'");
//		}
//		if (StringUtil.isNotBlank(financeNumber)) {
//			sql.append(" AND c.FINANCE_NUMBER like '%").append(financeNumber + "%'");
//		}
//		if (null != bulkstockInfoId) {
//			sql.append(" AND BULKSTOCK_INFO_ID =").append(bulkstockInfoId);
//		}
//		sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID, LOCATION_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE NOT IN(1, 13) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
		
		if (StringUtil.isNotBlank(warehouseName)) {
			sql.append(" AND v.WAREHOUSE_NAME = '").append(warehouseName).append("' ");
		}
		
		if (StringUtil.isNotBlank(bulkstockName)) {
			sql.append(" AND v.BULKSTOCK_NAME like '%").append(bulkstockName + "%'");
		}
		
		if (null != bulkstockInfoId) {
			sql.append(" AND v.BULKSTOCK_INFO_ID =").append(bulkstockInfoId);
		}
		
		if (null != enterpriseId) {
			sql.append(" AND v.ENTERPRISE_ID =").append(enterpriseId);
		}
		
//		sql.append(" AND v.PRODUCT_TYPE =").append(productType);
		
		Session session = SessionRepository.getCurrentSession();
		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("SPECIFICATION").addScalar("WAREHOUSE_ID").list();
		List<PickupBulkstockInfo> list = new ArrayList<>();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			if (BigDecimal.ZERO.compareTo((BigDecimal) os[0]) >= 0) {
				continue;
			}
			PickupBulkstockInfo pbi = new PickupBulkstockInfo();
			pbi.setWeight((BigDecimal) os[0]);
			pbi.setLocationId((String) os[1]);
			pbi.setBulkstockName((String) os[2]);
			pbi.setProductType(((Byte) os[3]).intValue());
			pbi.setBulkstockInfoId(((BigInteger) os[4]).longValue());
			pbi.setWarehouseName((String) os[5]);
			pbi.setLocationName((String) os[6]);
			pbi.setLocationArea((String) os[7]);
			pbi.setSpecifician((String) os[8]);
			pbi.setWarehouseId((String) os[9]);
			list.add(pbi);
		}
		SessionRepository.closeCurrentSession();
		return list;
	}

	@Override
	@Transactional
	public PageList<ContainerInventory> inquireBulkstockInventoryPageList(String financeContractSerialNumber, String enterpriseName, Long[] inventoryIds, Long financeId, String waybillNumber, Integer[] supervisionState, Integer inventoryState, String caseNumber, Long loanNoticeId, Integer productType, String financeNumber,String bulkstockName, PageCriteria page) {
		List<Long> f = financeContractService.inquireFinanceIdList(null, financeContractSerialNumber);
		if (financeId == null && f != null && f.size() > 0) {
			financeId = f.get(0);
		}
		List<SupervisionStateEnum> supervisionStates = new ArrayList<>();
		if (supervisionState != null && supervisionState.length > 0) {
			for (int s : supervisionState) {
				supervisionStates.add(SupervisionStateEnum.valueOf(s));
			}
		}
		List<Long> financeIds = financeApplicationService.getFinanceListIds(productType);
//		PageList<ContainerInventoryEntity> pageList = containerInventoryService.inquireContainerInventoryPageList(enterpriseName, inventoryIds, financeId, waybillNumber, inventoryState,
//				supervisionStates.toArray(new SupervisionStateEnum[supervisionStates.size()]), caseNumber, loanNoticeId, page);
		PageList<ContainerInventoryEntity> pageList = containerInventoryService.inquireContainerInventoryPageLists(financeIds,enterpriseName, inventoryIds, financeId, waybillNumber, inventoryState,
				supervisionStates.toArray(new SupervisionStateEnum[supervisionStates.size()]), caseNumber, loanNoticeId,financeNumber,bulkstockName, page);
		PageList<ContainerInventory> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (ContainerInventoryEntity bie : pageList) {
			resultList.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		
		return resultList;
	}

	@Override
	public PageList<ContainerInventory> inquireFinanceContainerInventoryPageList(String financeNumber, String beginDate, String endDate, String waybillNumber, String caseNumber, String enterpriseName, Long financeId, Integer inventoryState,
			Boolean inventoryLockState, PageCriteria page) {
		PageList<ContainerInventoryEntity> pageList = containerInventoryService.inquireContainerInventoryPageList(financeNumber, beginDate, endDate, waybillNumber, caseNumber, enterpriseName, financeId, inventoryState, page);
		PageList<ContainerInventory> resultList = new PageList<>(page, pageList.getTotalRecordCount());
		for (ContainerInventoryEntity bie : pageList) {
			resultList.add(BulkstockCastor.toContainerInventory(bie, inventoryLockState));
		}
		return resultList;
	}
	
	@Override
	public List<ContainerInventory> inquireFinanceContainerInventoryList(String caseNumber, String waybillNumber, Long financeId, Long loanNoticeId, Integer pickupState) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		
		if (ProductTypeEnum.PURCHASING_STORAGE == finance.getProductType() || ProductTypeEnum.PROXY_SALE == finance.getProductType()) {
			String sql = "SELECT FIN_CONTAINER_INVENTORY.INVENTORY_ID, PICKUP_ID, CASE_NUMBER, WAYBILL_NUMBER, WAREHOUSE_NAME, SUPERVISION_STATE, DELIVERY_NOTICE_ID, LOAN_NOTICE_ID, BULKSTOCK_NAME, SPECIFICATION, QUANTITY, WEIGHT, VOLUME, UNIT, SETTLEMENT_PRICE, ADJUSTMENT, FINANCE_PRICE, VALUATION_QUANTITY FROM FIN_CONTAINER_INVENTORY, FIN_CONTAINER_BULKSTOCK WHERE FIN_CONTAINER_BULKSTOCK.INVENTORY_ID = FIN_CONTAINER_INVENTORY.INVENTORY_ID ";
			Session session = SessionRepository.getCurrentSession();
			String condition = " ";
			if (StringUtil.isNotBlank(waybillNumber)) {
				condition += " AND FIN_CONTAINER_INVENTORY.WAYBILL_NUMBER LIKE '%" + waybillNumber + "%'";
			}
			if (StringUtil.isNotBlank(caseNumber)) {
				condition += " AND FIN_CONTAINER_INVENTORY.CASE_NUMBER LIKE '%" + caseNumber + "%'";
			}
			if (financeId != null) {
				condition += " AND FIN_CONTAINER_INVENTORY.FINANCE_ID = " + financeId;
			}
			if (loanNoticeId != null) {
				condition += " AND FIN_CONTAINER_INVENTORY.LOAN_NOTICE_ID = " + loanNoticeId;
			}
			if (null != pickupState) {
				if (2 == pickupState) {
					condition += " AND FIN_CONTAINER_INVENTORY.PICKUP_ID IS NULL";
				} else if(1 == pickupState) {
					condition += " AND FIN_CONTAINER_INVENTORY.PICKUP_ID IS NOT NULL";
				}
			}
			List<ContainerInventory> resultList = new ArrayList<>();
			List<Object> datas = session.createSQLQuery(sql + condition).addScalar("FIN_CONTAINER_INVENTORY.INVENTORY_ID").addScalar("CASE_NUMBER").addScalar("WAYBILL_NUMBER").addScalar("WAREHOUSE_NAME").addScalar("SUPERVISION_STATE").addScalar("BULKSTOCK_NAME").addScalar("SPECIFICATION").addScalar("QUANTITY").addScalar("WEIGHT").addScalar("VOLUME").addScalar("UNIT").addScalar("SETTLEMENT_PRICE").addScalar("ADJUSTMENT").addScalar("FINANCE_PRICE").addScalar("VALUATION_QUANTITY").addScalar("PICKUP_ID").list();
			for (Object l : datas) {
//				ContainerInventoryEntity entity = new ContainerInventoryEntity();
				ContainerInventory ci = new ContainerInventory();
				Object[] os = (Object[])l;
				ci.setInventoryId(((BigInteger)os[0]).longValue());
				ci.setFinanceId(financeId);
				ci.setCaseNumber((String)os[1]);
				ci.setWaybillNumber((String)os[2]);
				ci.setWarehouseName((String)os[3]);
				ci.setSupervisionState(Byte.toUnsignedInt((Byte)os[4]));
				if (os[15] != null) {
					ci.setPickupId(((BigInteger)os[15]).longValue());
				}
				ContainerBulkstock cb = new ContainerBulkstock();
				cb.setBulkstockName((String)os[5]);
				cb.setSpecification((String)os[6]);
				cb.setQuantity((BigDecimal)os[7]);
				cb.setWeight((BigDecimal)os[8]);
				cb.setVolume((BigDecimal)os[9]);
				cb.setUnit((String)os[10]);
				cb.setFinancePrice((BigDecimal)os[13]);
				cb.setValuationQuantity((BigDecimal)os[14]);
				cb.setFinanceValuation(cb.getValuationQuantity().multiply(cb.getFinancePrice()));
				ci.getContainerBulkstocks().add(cb);
				resultList.add(ci);
			}
			SessionRepository.closeCurrentSession();
			return resultList;
		} else {
			String sql = "SELECT FIN_CONTAINER_INVENTORY.INVENTORY_ID, PICKUP_ID, CASE_NUMBER, WAYBILL_NUMBER, WAREHOUSE_NAME, SUPERVISION_STATE, DELIVERY_NOTICE_ID, LOAN_NOTICE_ID, BULKSTOCK_NAME, SPECIFICATION, QUANTITY, WEIGHT, VOLUME, UNIT, SETTLEMENT_PRICE, ADJUSTMENT, FINANCE_PRICE, VALUATION_QUANTITY, TALLY_PRE_FILE, TALLY_SUFFIX_FILE, TALLYING_STATE, FILES_UUID, FACING_SLIP, CASE_SIZE FROM FIN_CONTAINER_INVENTORY, FIN_CONTAINER_BULKSTOCK, FIN_CONTAINER_INVENTORY_TALLY WHERE FIN_CONTAINER_BULKSTOCK.INVENTORY_ID = FIN_CONTAINER_INVENTORY.INVENTORY_ID AND FIN_CONTAINER_INVENTORY_TALLY.INVENTORY_ID = FIN_CONTAINER_INVENTORY.INVENTORY_ID ";
			Session session = SessionRepository.getCurrentSession();
			String condition = " ";
			if (StringUtil.isNotBlank(waybillNumber)) {
				condition += " AND FIN_CONTAINER_INVENTORY.WAYBILL_NUMBER LIKE '%" + waybillNumber + "%'";
			}
			if (StringUtil.isNotBlank(caseNumber)) {
				condition += " AND FIN_CONTAINER_INVENTORY.CASE_NUMBER LIKE '%" + caseNumber + "%'";
			}
			if (financeId != null) {
				condition += " AND FIN_CONTAINER_INVENTORY.FINANCE_ID = " + financeId;
			}
			if (loanNoticeId != null) {
				condition += " AND FIN_CONTAINER_INVENTORY.LOAN_NOTICE_ID = " + loanNoticeId;
			}
			if (null != pickupState) {
				if (2 == pickupState) {
					condition += " AND FIN_CONTAINER_INVENTORY.PICKUP_ID IS NULL";
				} else if(1 == pickupState) {
					condition += " AND FIN_CONTAINER_INVENTORY.PICKUP_ID IS NOT NULL";
				}
			}
			List<ContainerInventory> resultList = new ArrayList<>();
			List<Object> datas = session.createSQLQuery(sql + condition).addScalar("FIN_CONTAINER_INVENTORY.INVENTORY_ID").addScalar("CASE_NUMBER").addScalar("WAYBILL_NUMBER").addScalar("WAREHOUSE_NAME").addScalar("SUPERVISION_STATE").addScalar("BULKSTOCK_NAME").addScalar("SPECIFICATION").addScalar("QUANTITY").addScalar("WEIGHT").addScalar("VOLUME").addScalar("UNIT").addScalar("SETTLEMENT_PRICE").addScalar("ADJUSTMENT").addScalar("FINANCE_PRICE").addScalar("VALUATION_QUANTITY").addScalar("TALLY_PRE_FILE").addScalar("TALLY_SUFFIX_FILE").addScalar("PICKUP_ID").addScalar("TALLYING_STATE").addScalar("FILES_UUID").addScalar("FACING_SLIP").addScalar("CASE_SIZE").list();  
			for (Object l : datas) {
//				ContainerInventoryEntity entity = new ContainerInventoryEntity();
				ContainerInventory ci = new ContainerInventory();
				Object[] os = (Object[])l;
				ci.setInventoryId(((BigInteger)os[0]).longValue());
				ci.setFinanceId(financeId);
				ci.setCaseNumber((String)os[1]);
				ci.setWaybillNumber((String)os[2]);
				ci.setWarehouseName((String)os[3]);
				ci.setSupervisionState(Byte.toUnsignedInt((Byte)os[4]));
				ci.setTallyPreFile((String)os[15]);
				ci.setTallySuffixFile((String)os[16]);
				ci.setTallyingState(Byte.toUnsignedInt((Byte)os[18]));
				if (os[17] != null) {
					ci.setPickupId(((BigInteger)os[17]).longValue());
				}
				ContainerBulkstock cb = new ContainerBulkstock();
				cb.setBulkstockName((String)os[5]);
				cb.setSpecification((String)os[6]);
				cb.setQuantity((BigDecimal)os[7]);
				cb.setWeight((BigDecimal)os[8]);
				cb.setVolume((BigDecimal)os[9]);
				cb.setUnit((String)os[10]);
				cb.setFinancePrice((BigDecimal)os[13]);
				cb.setValuationQuantity((BigDecimal)os[14]);
				cb.setFinanceValuation(cb.getValuationQuantity().multiply(cb.getFinancePrice()));
				cb.setFilesUuid((String)os[19]);
				ci.setFacingSlip((String)os[20]);
				ci.setCaseSize((String)os[21]);
				
				ci.getContainerBulkstocks().add(cb);
				resultList.add(ci);
			}
			SessionRepository.closeCurrentSession();
			return resultList;
		}
		
		
	}

	@Override
	public List<ContainerInventory> inquireFacingSlipContainerInventoryList(String facingSlip) {
		if (!FinanceSessionContext.isLogistics() || FinanceSessionContext.getClerkId() == null) {
			return null;
		}
		Long clerkId = FinanceSessionContext.getClerkId();
		List<ContainerInventoryEntity> list = containerInventoryService.inquireFacingSlipContainerInventoryList(clerkId, facingSlip);
		List<ContainerInventory> results = new ArrayList<>(list.size());
		for (ContainerInventoryEntity bie : list) {
			results.add(BulkstockCastor.toContainerInventory(bie, Boolean.FALSE));
		}
		return results;
	}

	@Override
	public ContainerInventory inquireBulkstockInventoryDetail(Long inventoryId) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(inventoryId);
		return BulkstockCastor.toContainerInventory(inventory, Boolean.FALSE);
	}
	
	@Override
	public ContainerInventoryImages inquireInventoryImages(String waybillNumber, String caseNumber) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(waybillNumber, caseNumber);
		if (inventory == null) {
			throw new BusinessException("该箱不存在");
		}
		ContainerInventoryImages cii = new ContainerInventoryImages();
		ContainerInventoryTallyEntity cite = containerInventoryTallyService.inquireContainerInventoryTally(inventory.getInventoryId());
		
		cii.setCaseNumber(inventory.getCaseNumber());
		cii.setWaybillNumber(waybillNumber);
		if (StringUtils.isNotBlank(cite.getTallyPreFile())) {
			ImagesDetail id = new ImagesDetail();
			id.setImageRemark("理货前图片");
			StringBuffer sb = new StringBuffer();
			for (String f : cite.getTallyPreFile().split(",")) {
				if (StringUtils.isNotBlank(f)) {
					sb.append("http://www.zjjr56.com/finance/api/v1.0/downloadFile.file?fileUuid="+f).append(",");
				}
			}
			if (sb.length() > 0) {
				sb.deleteCharAt(sb.length() - 1);
			}
			id.setImageUrls(sb.toString());
			cii.getImages().add(id);
		}
		
		if (StringUtils.isNotBlank(cite.getTallySuffixFile())) {
			ImagesDetail id = new ImagesDetail();
			id.setImageRemark("理货后图片");
			StringBuffer sb = new StringBuffer();
			for (String f : cite.getTallyPreFile().split(",")) {
				if (StringUtils.isNotBlank(f)) {
					sb.append("http://www.zjjr56.com/finance/api/v1.0/downloadFile.file?fileUuid="+f).append(",");
				}
			}
			if (sb.length() > 0) {
				sb.deleteCharAt(sb.length() - 1);
			}
			id.setImageUrls(sb.toString());
			cii.getImages().add(id);
		}
		
		List<ContainerBulkstockEntity> containerBulkstockList = containerBulkstockService.inquireContainerBulkstockList(inventory.getInventoryId());
		for (ContainerBulkstockEntity cbe : containerBulkstockList) {
			if (StringUtils.isNotBlank(cbe.getFilesUuid())) {
				ImagesDetail id = new ImagesDetail();
				id.setImageRemark("货物图片");
				StringBuffer sb = new StringBuffer();
				for (String f : cbe.getFilesUuid().split(",")) {
					if (StringUtils.isNotBlank(f)) {
						sb.append("http://www.zjjr56.com/finance/api/v1.0/downloadFile.file?fileUuid="+f).append(",");
					}
				}
				if (sb.length() > 0) {
					sb.deleteCharAt(sb.length() - 1);
				}
				id.setImageUrls(sb.toString());
				cii.getImages().add(id);
			}
		}
		
		return cii;
	}
	
	@Override
	public List<ContainerInfos> inquireContainerInfos(String waybillNumber, Long enterpriseId, String enterpriseName) {
		List<ContainerInfos> cis = new ArrayList<>();
		if (StringUtil.isNotBlank(enterpriseName)) {
			List<EnterpriseEntity> ees = enterpriseService.inquireEnterpriseByEnterpriseName(enterpriseName);
			if (ees != null && ees.size() == 1) {
				enterpriseId = ees.get(0).getEnterpriseId();
			}
		}
//		if (StringUtils.isNotBlank(waybillNumber) || null != enterpriseId || StringUtil.isNotBlank(enterpriseName)) {
			List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(waybillNumber, enterpriseId, 1);
			String owb = "";
			StringBuffer sb = new StringBuffer();
			ContainerInfos ci = new ContainerInfos();
			for (int i = 0; i < cies.size(); i++) {
				ContainerInventoryEntity cie = cies.get(i);
				if (cie == null || StringUtils.isBlank(cie.getWaybillNumber()) || StringUtils.isBlank(cie.getCaseNumber())) {
					continue;
				}
				if (owb.equals(cie.getWaybillNumber())) {
					sb.append(cie.getCaseNumber()).append(",");
					if (i == cies.size() - 1) {
						ci.setCaseNumbers(sb.deleteCharAt(sb.length() - 1).toString());
						cis.add(ci);
					}
				} else {
					if (StringUtils.isNotBlank(owb)) {
						ci.setCaseNumbers(sb.deleteCharAt(sb.length() - 1).toString());
						cis.add(ci);
					}
					sb = new StringBuffer();
					ci = new ContainerInfos();
					ci.setWaybillNumber(cie.getWaybillNumber());
					owb = cie.getWaybillNumber();
					sb.append(cie.getCaseNumber()).append(",");
					if (i == cies.size() - 1) {
						ci.setCaseNumbers(sb.deleteCharAt(sb.length() - 1).toString());
						cis.add(ci);
					}
				}
			}
			return cis;
//		} else {
//			throw new BusinessException("运单号和企业Id不能同时为空!");
//		}
	}

	@Override
	public ContainerInventoryTrackingDetail inquireContainerInventoryTrackingDetail(Long inventoryId) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(inventoryId);
		if (StringUtils.isBlank(inventory.getCaseNumber())) {
			throw new BusinessException("该箱箱号为空");
		}
		if (StringUtils.isBlank(inventory.getWaybillNumber())) {
			throw new BusinessException("该箱提单号为空");
		}
		String url = ConfigPropertites.getProperties("trace.goods.service");
		Map<String, String> params = new HashMap<>();
		params.put("boxNO", inventory.getCaseNumber());
		params.put("billNO", inventory.getWaybillNumber());
		String responseText = HttpClientHelper.post(url, params);
		ContainerInventoryTrackingDetail result = JSON.toBean(responseText, ContainerInventoryTrackingDetail.class);
		return result;
	}

	@Override
	public ContainerInventoryTrackingDetail inquireFinanceContainerInventoryTrackingDetail(String financeNumber, String waybillNumber, String caseNumber) {
//		List<ContainerInventoryEntity> inventories = containerInventoryService.inquireContainerInventory(financeNumber, waybillNumber, caseNumber);
//		if (inventories.isEmpty()) {
//			throw new BusinessException("查不到该箱信息");
//		}
//		waybillNumber = "ATTJNS16828410";
		ContainerInventoryTrackingDetail result = new ContainerInventoryTrackingDetail();

		Map<String, String> params = new HashMap<>();
		params.put("billNumber", waybillNumber);
		params.put("boxNumber", caseNumber);
		params.put("Key", FinanceConstant.HANDLE_SUITCASE_KEY);
		
		String responseText = ServiceClientHelper.invoke("http://www.antong56.com/services/FinancialPlatformService?wsdl", "getContainerTrace", params);
		
		result = JSON.toBean(responseText, ContainerInventoryTrackingDetail.class);
		return result;

	}

	@Transactional
	@Override
	public void updateContainerInventoryWaybillNumber(Long[] inventoryIds, String waybillNumber) {
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(inventoryIds);
		for (ContainerInventoryEntity cie : cies) {
			cie.setWaybillNumber(waybillNumber);
			containerInventoryService.renovateContainerInventory(cie);
		}
	}

	@Override
	public List<ContainerInventoryHistory> inquireFinanceContainerInventoryHistoryList(String caseNumber, String waybillNumber) {
		List<ContainerInventoryHistoryEntity> pages = containerInventoryHistoryService.inquireRecieveNoticeContainerInventory(waybillNumber, caseNumber);
		List<ContainerInventoryHistory> results = new ArrayList<>();
		for (ContainerInventoryHistoryEntity cihe : pages) {
			ContainerInventoryHistory cie = new ContainerInventoryHistory();
			cie = BulkstockCastor.toContainerInventoryHistory(cihe);
			results.add(cie);
		}
		return results;
	}

	@Override
	public List<ContainerInventoryHistory> inquireEmptyFinanceContainerInventoryHistoryList(String waybillNumber, String caseNumber) {
		List<ContainerInventoryHistoryEntity> pages = containerInventoryHistoryService.inquireEmptyFinanceContainerInventory(waybillNumber, caseNumber);
		List<ContainerInventoryHistory> results = new ArrayList<>();
		for (ContainerInventoryHistoryEntity cihe : pages) {
			ContainerInventoryHistory cie = new ContainerInventoryHistory();
			cie = BulkstockCastor.toContainerInventoryHistory(cihe);
			results.add(cie);
		}
		return results;
	}

	@Override
	public ContainerInventoryHistory inquireFinanceContainerInventoryHistory(Long inventoryHistoryId) {
		ContainerInventoryHistoryEntity entity = containerInventoryHistoryService.inquireContainerInventory(inventoryHistoryId);
		ContainerInventoryHistory cie = BulkstockCastor.toContainerInventoryHistory(entity);
		return cie;
	}
	
	@Transactional
	@Override
	public Map<String,String> changeBill(String originalNumber,String type,String newNumbers,String key) {
		logger.info(" originalNumber====================" + originalNumber);
		logger.info(" type====================" + type);
		logger.info(" newNumbers====================" + newNumbers);
		logger.info(" key====================" + key);
		
		FinanceChangeBillLogService financeChangeBillLogService = ComponentFactory.loadClass(FinanceChangeBillLogService.class);
		//数据库轨迹记录
		Map<String,String> map=new HashMap<String,String>();
		if(key==null || !"HKdj67s7hhjQKCNVfggr4242ftasdSFDGS".equals(key)){
			map.put("message", "验证key不通过!");
			map.put("result", "0");
			return map;
		} 
		if(StringUtils.isEmpty(type)){  //判断操作类型
			map.put("message", "type为空!");
			map.put("result", "0");
			return map;
		} 
		if(StringUtils.isEmpty(originalNumber)){
			map.put("message", "原运单号为空!");
			map.put("result", "0");
			return map;
		} 
		if(StringUtils.isEmpty(newNumbers)){
			map.put("message", "新运单号为空!");
			map.put("result", "0");
			return map;
		}
		
		//根据运单号查询箱信息
		List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(originalNumber, null, null);
		if(cies==null || cies.size()==0){
			map.put("message", "运单号:"+originalNumber+"查询不到箱信息!");
			map.put("result", "0");
			return map;
		}
		if(type.equals("1")){
			for (ContainerInventoryEntity cie : cies) {
				cie.setWaybillNumber(newNumbers);
				containerInventoryService.renovateContainerInventory(cie);
			}
			//日志
			FinanceChangebillLogEntity financeChangebillLogEntity=new FinanceChangebillLogEntity(originalNumber,type,newNumbers,"");
			financeChangeBillLogService.createChangebillLogEntity(financeChangebillLogEntity);  //日志
		}else if(type.equals("2")){ //拆单
		
			JSONArray json = JSONArray.fromObject(newNumbers);
			List<BillInfo> list=JSONArray.toList(json,BillInfo.class);
			Map<String,String> outMap=new HashMap<String,String>();  //key 箱号  ; value 运单号
			for(BillInfo info:list){
				if(info!=null &&info.getContainer()!=null){
					String [] containers=info.getContainer().split(",");
					for(int i=0;i<containers.length;i++){
						if(!StringUtils.isEmpty(containers[i]))
						outMap.put(containers[i], info.getBill());
					}
					//日志
					FinanceChangebillLogEntity financeChangebillLogEntity=new FinanceChangebillLogEntity(originalNumber,type,info.getBill(),info.getContainer());
					financeChangeBillLogService.createChangebillLogEntity(financeChangebillLogEntity); 
				}
			}
			//更新运单号
			for (ContainerInventoryEntity cie : cies) {
				if(cie!=null && outMap.containsKey(cie.getCaseNumber())){  //查询是否包含箱号
					cie.setWaybillNumber(outMap.get(cie.getCaseNumber()));
					containerInventoryService.renovateContainerInventory(cie);
				}
			}	
		}
		map.put("message", "操作成功!");
		map.put("result", "1");
		return map;
	}

	@Override
	public List<ContainerInventoryLog> inquireContainerInventoryLogList(Long inventoryId) {
		List<FinanceContainerLogEntity> fcles = financeContainerLogService.inquireFinanceContainerLogList(inventoryId);
		List<ContainerInventoryLog> cils = new ArrayList<>();
		for (FinanceContainerLogEntity fcle : fcles) {
			ContainerInventoryLog cil = new ContainerInventoryLog();
			BeanUtils.copyProperties(fcle, cil);
			cils.add(cil);
		}
		return cils;
	}

	@Override
	@Transactional
	public void createContainerInventoryLog(String caseNumber, String operator, String remark) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(null, caseNumber);
		if (inventory == null) {
			throw new BusinessException("该货箱不存在！");
		}
		FinanceContainerLogEntity fcle = new FinanceContainerLogEntity();
		fcle.setInventoryId(inventory.getInventoryId());
		fcle.setOperator(operator);
		fcle.setRemark(remark);
		financeContainerLogService.createFinanceContainerLog(fcle);
	}

	@Override
	public Long inquireFinanceIdBycontainer(String caseNumber, String waybillNumber) {
		ContainerInventoryEntity inventory = containerInventoryService.inquireContainerInventory(waybillNumber, caseNumber);
		if (inventory == null) {
			throw new BusinessException("该箱不存在！");
		}
		return inventory.getFinanceId();
	}
}
